package com.njupt.swg.threadstudyjimin.item04.atomic;

import com.njupt.swg.threadstudyjimin.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

@ThreadSafe
@Slf4j
public class AtomicBooleanTest {
    private static AtomicBoolean atomicBoolean = new AtomicBoolean();
    private static int clientTotal = 5000;
    private static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        System.out.println(atomicBoolean.get());
        for(int i=0;i<clientTotal;i++){
            threadPool.execute(() -> {
                try{
                    semaphore.acquire();
                    test();
                    semaphore.release();
                }catch (Exception e){
                    log.error("semaphore exception");
                }
            });
            countDownLatch.countDown();
        }

        countDownLatch.await();
        threadPool.shutdown();

        System.out.println("执行结果为："+atomicBoolean.get());
    }

    //第一个进来变成true之后，后面所有的都不能再进这个if了
    //这里有5000个线程，只执行一次这个代码的场景
    private static void test(){
        if(atomicBoolean.compareAndSet(false,true)){
            System.out.println("执行了compareAndSet方法...");
        }
    }
}
